<template>
  <div class="login-container">
    <van-nav-bar title="登录" left-arrow @click-left="onClickLeft" />
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="loginForm.loginname"
          name="手机号"
          label="手机号"
          placeholder="请输入手机号"
          :rules="[
            { required: true, message: '请填写手机号' },
            {
              pattern: /^1[3-9]\d{9}$/,
              message: '手机号不合法'
            }
          ]"
        />
        <van-field
          v-model="loginForm.password"
          type="password"
          name="密码"
          label="密码"
          placeholder="请输入密码"
          :rules="[
            { required: true, message: '请填写密码' },
            {
              pattern: /^\w{6,16}$/,
              message: '密码必须是6-16位'
            }
          ]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { showSuccessToast, showFailToast } from 'vant'
import { useRoute, useRouter } from 'vue-router'
import { reactive } from 'vue'
import { login } from '../../api/user'
import { useUserStore } from '../../store/user'

const store = useUserStore()

const loginForm = reactive({
  loginname: '17704051019',
  password: '123456'
})

const route = useRoute()
const router = useRouter()

const onClickLeft = () => {
  router.back()
}

const onSubmit = async () => {
  const res = await login(loginForm)

  if (res.code === 200) {
    // 保存token到仓库中
    store.setToken(res.data.token)

    // 提示、跳转到layout页面
    showSuccessToast({
      message: res.message,
      duration: 800,
      onClose: () => {
        if (route.query.redirect) {
          router.push(route.query.redirect)
        } else {
          router.push('/')
        }
      }
    })
  } else {
    showFailToast(res.message)
  }
}
</script>

<style scoped>
.login-container {
  height: 100%;
}
</style>
